package com.cloud.gatewaySpringSecurity.handler;

import com.cloud.gatewaySpringSecurity.constant.TokenConstant;
import com.cloud.gatewaySpringSecurity.pojo.TokenUser;
import com.cloud.gatewaySpringSecurity.properties.RsaKeyProperties;
import com.cloud.gatewaySpringSecurity.service.RedisService;
import com.cloud.gatewaySpringSecurity.utils.JwtUtil;
import com.cloud.gatewaySpringSecurity.utils.SaveMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * @author zhozixiong
 * @date 2023/03/02
 *
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        //封装用户信息
        TokenUser tokenUser = new TokenUser();
        tokenUser.setUid((String) usernamePasswordAuthenticationToken.getPrincipal());
        tokenUser.setRole((String) usernamePasswordAuthenticationToken.getCredentials());
        Collection<GrantedAuthority> globalExceptionHandlers = usernamePasswordAuthenticationToken.getAuthorities();
        List<String> list = new ArrayList();
        for(GrantedAuthority grantedAuthority : globalExceptionHandlers) {
            list.add(grantedAuthority.getAuthority());
        }
        tokenUser.setAuthority(list);
        //生成唯一id
        String id = JwtUtil.createJti();
        //生成token
        String token = JwtUtil.generateTokenExpireInMinutes(tokenUser, rsaKeyProperties.getPrivateKey(), id);
        //将登录信息记录到redis中,并设置过期时间
        redisService.setObject(TokenConstant.TOKEN_REDIS_PREFIX + id, "", 5000);
        Map<String, Object> map = new HashMap<>(2, 1);
        map.put(HttpHeaders.AUTHORIZATION, TokenConstant.TOKEN_PREFIX + token);
        return SaveMessage.save(response, HttpStatus.OK, map);
    }
}
